import React, { useState, useEffect } from 'react'
import { getBlogDetail } from '@/api/index'
import style from './index.module.scss'
import { style as markDownStye, mdParser } from '@/utils/markdown'
import { cp, showTime } from '@/utils/utils'
import event from '@/utils/event'
import Comment from './comment'
import BackTop from '@/components/backTop'
import { useRouteMatch } from 'react-router-dom'

interface BlogDetail extends BlogList {
  markDownText: string
}

export default () => {
  const match = useRouteMatch<{ id?: string }>()
  const id = Number(match.params.id)
  const [detail, setDetail] = useState<BlogDetail>({
    blogId: id,
    creationTime: '',
    content: '',
    cover: '',
    title: '',
    markDownText: '',
    viewCount: 0,
    commentList: [],
  })
  useEffect(() => {
    const getData = async () => {
      const { data } = await getBlogDetail({ blogId: id })
      renderMd(data)
    }
    // 解析md
    const renderMd = (data: BlogDetail) => {
      let tocArrays: tocArrayType = []
      const markDownText = mdParser
        .set({
          tocCallback(_tocMarkdown: any, tocArray: tocArrayType) {
            tocArrays = tocArray
          },
        })
        .renders(data.content)
      setDetail({ ...data, markDownText })
      const domPositionTop = computTitleTop(tocArrays)
      event.emit('blogContent', tocArrays, domPositionTop)
    }
    // 计算所有标签的高度
    function computTitleTop(ids: tocArrayType) {
      const domPositionTop = []
try {
  for (const list of ids) {
    const id = list.anchor
    const element = document.querySelector('#' + id)
    domPositionTop.push((element as HTMLElement).offsetTop)
  }
} catch (error) {
  console.log(error)
}
      return domPositionTop
    }
    // 监听留言成功事件

    getData()
    return destrory
  }, [id]) 
  useEffect(() => {
    event.on('addBlogComment', (newComment) => {
      const newDetail = cp(detail)
      newDetail.commentList.unshift(newComment)
      setDetail(newDetail)
    })
  }, [detail])
  function destrory() {
    event.emit('destroyDetai')
  }
  return (
    <div id="detail" className={style.detail}>
      <BackTop target={() => document.querySelector('#detail')}></BackTop>
      <div className={style.detail_container}>
        <div className={style.title}>{detail.title}</div>
        <div className={style.info}>
          <div className={style.time}>{showTime(detail.creationTime)}</div>
          <div className={style.view_count}>阅读量:{detail.viewCount}</div>
        </div>
        {detail.cover && (
          <div className={style.cover_row}>
            <img src={detail.cover} alt="" />
          </div>
        )}

        <div className={style.markdown}>
          <div
            className={markDownStye.markdown_body}
            dangerouslySetInnerHTML={{
              __html: detail.markDownText,
            }}
          ></div>
        </div>
        <div id="footerDom"></div>
        <Comment commentList={detail.commentList} />
      </div>
    </div>
  )
}
